import axios from 'axios'
import qs from 'qs'
import {
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'
import {
	getToken
} from '@/utils/auth'
import {
	formatDateByFmt
} from '@/utils/util.js'

import SETTING from '@/settings'

const {
	WEBAPI,
	PREAPI,
	PROXY
} = SETTING

// create an axios instance
const service = axios.create({
	proxy: PROXY,
	baseURL: PROXY ? PREAPI : WEBAPI + PREAPI, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 30 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		if (getToken()) {
			config.headers['Authorization'] = getToken()
		}
		if (config.content_type === 'json') {} else {
			config.data = qs.stringify(config.data, {
				allowDots: true
			})
		}
		config.responseType = 'blob'
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const blob = new Blob([response.data], {
			type: 'text/plain,charset=UTF-8'
		}) // 构造一个blob对象来处理数据
		const fileName = response.config.fileName;
		// IE10以上
		if ('msSaveOrOpenBlob' in navigator) {
			window.navigator.msSaveOrOpenBlob(blob, fileName)
			return
		}

		// 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
		if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
			const link = document.createElement('a') // 创建a标签
			link.download = fileName // a标签添加属性
			link.style.display = 'none'
			link.href = URL.createObjectURL(blob)
			document.body.appendChild(link)
			link.click() // 执行下载
			URL.revokeObjectURL(link.href) // 释放url
			document.body.removeChild(link) // 释放标签
		} else { //其他浏览器
			navigator.msSaveBlob(blob, fileName)
		}

		return;
	},
	error => {
		console.log('err' + error) // for debug
		Message({
			message: error,
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service
